/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sk.lieskove.jianghongtiao.common.system;

import org.apache.log4j.Logger;

import java.io.*;

/**
 * Run system command and capture the output
 * @author xjuraj e-mail: jjurco.sk_gmail.com
 */
public class RunCommand implements Serializable {
    
    private static transient Logger log = Logger.getLogger(RunCommand.class);
    
    public static String runCommand(String command){
        File actualPath = new File(".");
        log.debug("RunCommand: "+command+" in path: "+actualPath.getAbsolutePath());
        String s = null;
        StringBuilder textBuffer = new StringBuilder();

        try {
            // using the Runtime exec method:
            Process p = Runtime.getRuntime().exec(command);
            
            // read the output from the command
            BufferedReader stdInput = new BufferedReader(new 
                 InputStreamReader(p.getInputStream()));
            while ((s = stdInput.readLine()) != null) {
                textBuffer.append(s).append(System.lineSeparator());
            }
            // read any errors from the attempted command
            BufferedReader stdError = new BufferedReader(new 
                 InputStreamReader(p.getErrorStream()));
            while ((s = stdError.readLine()) != null) {
                log.error(s + System.lineSeparator());
            }
            return textBuffer.toString().trim();
        }
        catch (IOException e) {
            log.error("IOException thrown for command: "+command, e);
        }
        return null;
    }
}
